//
//  QRCodeCreateController.swift
//  WBDemo
//
//  Created by Jin on 19/04/2018.
//  Copyright © 2018 com.baidu.123. All rights reserved.
//

import UIKit

class QRCodeCreateController: UIViewController {

    @IBOutlet weak var qrcodeImageView:UIImageView!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        let filter = CIFilter(name: "CIQRCodeGenerator")
        filter?.setDefaults()
        filter?.setValue("二哈哈".data(using: .utf8), forKey: "inputMessage")
        let ciImage = filter?.outputImage
        qrcodeImageView.image = createNonInterpolatedUIImageFormCIImage(image: ciImage!, size: 300)
    }

    //生成高清二维码
    private func createNonInterpolatedUIImageFormCIImage(image: CIImage, size: CGFloat) -> UIImage {
        
        //CIImage没有frame与bounds属性,只有extent属性
        
        let ciextent: CGRect = image.extent.integral
        
        let scale: CGFloat = min(size/ciextent.width, size/ciextent.height)
        
        let context = CIContext(options: nil)  //创建基于GPU的CIContext对象,性能和效果更好
        
        let bitmapImage: CGImage = context.createCGImage(image, from: ciextent)! //CIImage->CGImage
        
        let width = ciextent.width * scale
        
        let height = ciextent.height * scale
        
        let cs: CGColorSpace = CGColorSpaceCreateDeviceGray() //灰度颜色通道
        
        let info_UInt32 = CGImageAlphaInfo.none.rawValue
        
        let bitmapRef = CGContext(data: nil, width: Int(width), height: Int(height), bitsPerComponent: 8, bytesPerRow: 0, space: cs, bitmapInfo: info_UInt32)! //图形上下文，画布
        
        bitmapRef.interpolationQuality = CGInterpolationQuality.none //写入质量
        
        bitmapRef.scaleBy(x: scale, y: scale) //调整“画布”的缩放
        
        bitmapRef.draw(bitmapImage, in: ciextent) //绘制图片
        
        let scaledImage: CGImage = bitmapRef.makeImage()! //保存
        
        return UIImage(cgImage: scaledImage)
    }
    
}
